import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Avatar, List, Grid, Button, Toast } from "antd-mobile";
import { UserOutline, HeartFill, StarFill, FireFill } from "antd-mobile-icons";
import { getUserInfo, clearUserData } from "../../../utils/tokenManager";

function Index() {
    const navigate = useNavigate();
    const [userInfo, setUserInfo] = useState(getUserInfo());

    const handleLogin = () => navigate('/login');
    const handleRegister = () => navigate('/register');
    const handleLogout = () => {
        clearUserData();
        setUserInfo(getUserInfo());
        Toast.show({ content: '已退出登录', duration: 1200 });
    };

    // 监听登录状态变化
    useEffect(() => {
        const updateUserInfo = () => {
            setUserInfo(getUserInfo());
        };

        // 页面显示时更新用户信息
        updateUserInfo();

        // 监听 storage 变化（当其他页面修改了 localStorage 时）
        const handleStorageChange = (e) => {
            if (e.key === 'token' || e.key === 'touxiang' || e.key === 'userId' || e.key === 'userEmail') {
                updateUserInfo();
            }
        };

        window.addEventListener('storage', handleStorageChange);
        
        // 添加自定义事件监听器，用于同页面内的状态更新
        const handleUserDataChange = () => {
            updateUserInfo();
        };
        
        window.addEventListener('userDataChanged', handleUserDataChange);

        return () => {
            window.removeEventListener('storage', handleStorageChange);
            window.removeEventListener('userDataChanged', handleUserDataChange);
        };
    }, []);

    const ProfileSection = () => (
        <div style={{
            background: 'linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%)',
            padding: '20px 16px',
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            borderBottom: '1px solid #e8f3ff'
        }}>
            <Avatar
                src={userInfo?.avatar || undefined}
                style={{
                    '--size': '56px',
                    backgroundColor: '#1677ff',
                    color: '#fff'
                }}
            >
                {!userInfo?.avatar && <UserOutline />}
            </Avatar>
            <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                    fontSize: '16px',
                    fontWeight: 600,
                    color: '#0d1a26',
                    marginBottom: '4px',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                }}>
                    {userInfo?.isLoggedIn ? (userInfo?.email || `用户 ${userInfo?.userId || ''}`) : '未登录'}
                </div>
                <div style={{ fontSize: '12px', color: '#667085' }}>
                    {userInfo?.isLoggedIn ? '欢迎回来，祝您健康每一天' : '登录后可同步收藏、订单与健康档案'}
                </div>
            </div>
            {userInfo?.isLoggedIn ? (
                <Button size="mini" color="danger" onClick={handleLogout}>退出</Button>
            ) : (
                <div style={{ display: 'flex', gap: 8 }}>
                    <Button size="mini" color="primary" onClick={handleLogin}>登录</Button>
                    <Button size="mini" color="default" onClick={handleRegister}>注册</Button>
                </div>
            )}
        </div>
    );

    const QuickActions = () => (
        <div style={{ padding: '12px 16px', backgroundColor: '#fff' }}>
            <Grid columns={4} gap={12}>
                {[
                    { key: 'consult', label: '我的咨询', color: '#ff9f6b', icon: '💬' },
                    { key: 'favorite', label: '我的收藏', color: '#34c3a0', icon: <StarFill color="#fff" /> },
                    { key: 'health', label: '健康档案', color: '#8ab5ff', icon: '📄' },
                    { key: 'points', label: '健康值', color: '#ff7950', icon: <FireFill color="#fff" /> }
                ].map(item => (
                    <Grid.Item key={item.key}>
                        <div
                            onClick={() => Toast.show({ content: `${item.label} 敬请期待` })}
                            style={{ textAlign: 'center', cursor: 'pointer' }}
                        >
                            <div style={{
                                width: 56,
                                height: 56,
                                margin: '0 auto 8px',
                                borderRadius: '50%',
                                backgroundColor: item.color,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                boxShadow: '0 2px 8px rgba(0,0,0,0.08)'
                            }}>
                                <span style={{ fontSize: 22, color: '#fff' }}>{item.icon}</span>
                            </div>
                            <div style={{ fontSize: 12, color: '#333' }}>{item.label}</div>
                        </div>
                    </Grid.Item>
                ))}
            </Grid>
        </div>
    );

    return (
        <div style={{
            minHeight: '100vh',
            backgroundColor: '#f5f5f5',
            paddingBottom: '60px'
        }}>
            <ProfileSection />

            <div style={{ height: 8 }}></div>
            <QuickActions />

            <div style={{ height: 8 }}></div>
            <List header="常用功能" style={{ background: '#fff' }}>
                <List.Item onClick={() => Toast.show({ content: '账户与安全 敬请期待' })} arrow>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>🔒</span>
                        <span>账户与安全</span>
                    </div>
                </List.Item>
                <List.Item onClick={() => Toast.show({ content: '我的订单 敬请期待' })} arrow>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>🧾</span>
                        <span>我的订单</span>
                    </div>
                </List.Item>
                <List.Item onClick={() => Toast.show({ content: '帮助与反馈 敬请期待' })} arrow>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>🆘</span>
                        <span>帮助与反馈</span>
                    </div>
                </List.Item>
                <List.Item onClick={() => Toast.show({ content: '设置 敬请期待' })} arrow>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>⚙️</span>
                        <span>设置</span>
                    </div>
                </List.Item>
            </List>

            <div style={{ height: 12 }}></div>
            <List header="关于" style={{ background: '#fff' }}>
                <List.Item arrow onClick={() => Toast.show({ content: '好医生 v1.0.0' })}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>🏥</span>
                        <span>关于好医生</span>
                    </div>
                </List.Item>
            </List>
        </div>
    );
}

export default Index;


